package stack;

import java.util.Stack;

public class leetcode402移掉K位数字 {
    public String removeKdigits(String num, int k) {
        int length = num.length();
        Stack<Character> stack = new Stack<>();
        int index = 0;
        while (index < length) {
            char c = num.charAt(index);
            while (!stack.isEmpty() && stack.peek() > c && k > 0) {
                stack.pop();
                k--;
            }
            index++;
            stack.push(c);
        }
        while (k > 0) {
            stack.pop();
            k--;
        }
        StringBuilder builder = new StringBuilder();
        while (!stack.isEmpty()){
            builder.insert(0, stack.pop());
        }
        StringBuilder result = new StringBuilder();
        boolean begin = true;
        for (char c : builder.toString().toCharArray()) {
            if (c != '0') {
                begin = false;
            }
            if (!begin) {
                result.append(c);
            }
        }
        if (result.length() == 0) {
            return "0";
        }
        return result.toString();
    }
}
